package com.edu.user.utils;

import com.edu.user.domain.dto.NotificationDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;


public class NotificationListener {

    private final SimpMessagingTemplate messagingTemplate;
    private final ObjectMapper objectMapper;

    @Autowired
    public NotificationListener(SimpMessagingTemplate messagingTemplate, ObjectMapper objectMapper) {
        this.messagingTemplate = messagingTemplate;
        this.objectMapper = objectMapper;
    }

    @RabbitListener(queues = "notification.queue")
    public void receiveNotification(NotificationDTO notificationDTO) {
        try {
            // 将 NotificationDTO 对象转换为 JSON 字符串
            String messageJson = objectMapper.writeValueAsString(notificationDTO);
            // 发送 JSON 字符串到前端
            messagingTemplate.convertAndSendToUser(
                    notificationDTO.getUserId().toString(),
                    "/topic/notifications",
                    messageJson
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
